const app = getApp();
const { request }  = require('../../request/index.js');
Component({
    properties: {
        message_data:{
            type:Array,
            value:[]
        },
    },
    data: {
        NavbarHeight:app.globalData.navBarHeight + app.globalData.statusBarHeight,
        WindowWidth:app.globalData.windowWidth,
        proData:[],
        groupDataArr:[],
        groupCollectDataArr:[],
        showDate:[],
        pickerDate:[],
        nowDate:app.globalData.nowTime.substring(0,4)+app.globalData.nowTime.substring(5,7),
        arrayYear:[],
        arrayMonth:[],
        arrayMonthThisYear:[],
        YearFlag:1,
        pickerActive:0,
        maskActive:0,
        posScroll:"item0",
        cardShowId:1,
        cardShowActive:0,
        collectFlag:0,
        message_data_collect:[],
        cardFront:0,
        cardBack:0,
        CardFrontFlag:1,
        styleCardFront:'',
        styleCardBack:'',
        RotateCardFront:0,
        RotateCardBack:-180,
    },
    /**
     * 组件的方法列表
     */
    attached(){
        console.log(this.properties.message_data);
        this.setData({
            proData:this.properties.message_data
        })
        this.splitDataArray();
        this.dealDate();
        //console.log(this.data.groupDataArr)
    },
    pageLifetimes: {
        show: function() {
            this.setData({
                proData:this.properties.message_data
            })
            this.splitDataArray();
        },
        resize: function(size) {
            // 页面尺寸变化
        }
    },
    methods: {
        //选择器的时间
        dealDate(){
            var res = new Array();
            for(let i=2015; i<=parseInt(this.data.nowDate.substr(0,4));i++){
                res.push(i.toString()+"年");
            }
            this.setData({
                arrayYear:res,
            })
            var res = new Array();
            for(let i=1; i<=12;i++){
                res.push(i.toString()+"月");
            }
            this.setData({
                arrayMonth:res,
            })
            var res = new Array();
            for(let i=1; i<=parseInt(this.data.nowDate.substr(4,2));i++){
                res.push(i.toString()+"月");
            }
            this.setData({
                arrayMonthThisYear:res,
            })
            var year=parseInt(this.data.nowDate.substr(0,4))-2015;
            var month=parseInt(this.data.nowDate.substr(4,2))-1;
            this.setData({
                showDate:[month,year],
            })
        },

        //准备
        ready() {
            this.scrollToPos();
        },

        //处理输入数据，分割成收藏和未收藏
        splitDataArray(){
            let groupData = new Map()
            this.data.proData.forEach(item => {
                // 将数据自带的时间字段分割成两段，日期用于分组，时间用于展示
                let date= item.date.substr(0,7);
                if(!groupData.has(date)) {
                    groupData.set(date, [item])
                } else {
                    groupData.get(date).push(item)
                }
            })
            let groupDataArr = [...groupData.entries()];
            // console.log(groupDataArr);
            this.setData({
                    groupDataArr:groupDataArr
                }
            )
            let groupDataCollect = new Map()
            this.data.proData.forEach(item => {
                    if(item.collect===1){
                        console.log(item);
                        let date= item.date.substr(0,7);
                        if(!groupDataCollect.has(date)) {
                            groupDataCollect.set(date, [item])
                        } else {
                            groupDataCollect.get(date).push(item)
                        }
                    }
                }
            )
            let groupDataCollectArr = [...groupDataCollect.entries()];
            this.setData({
                    groupCollectDataArr:groupDataCollectArr
                }
            )
            var res = new Array();
            this.data.proData.forEach(item => {
                if(item.collect===1){
                    res.push(item);
                }
            })
            this.setData({
                message_data_collect:res,
            })
        },

        //出现时间选择器
        DatePickerItemTap() {
            wx.hideTabBar({
                fail: function () {
                    setTimeout(function () { // 做了个延时重试一次，作为保底。
                        wx.hideTabBar();
                    }, 500)
                }
            });
            this.setData({
                pickerActive: 1,
                maskActive: 1,
            })
            // console.log(this.data.pickerActive+"ok");
        },

        //时间选择器改变
        bindChange(e) {
            // console.log('picker下拉项发生变化后，下标为：', e.detail);
            const month = e.detail.value[0];
            const year = e.detail.value[1];
            // console.log(year);
            // 当前年为2023
            if (year == 8) {
                this.setData({
                    YearFlag: 1,
                })
            } else {
                this.setData({
                    YearFlag: 0,
                })
            }
            this.setData({
                pickerDate: [month, year],
            })
        },

        //关闭时间选择器
        ClosePickerItemTap() {
            // console.log(this.data.pickerDate)
            wx.showTabBar({
                fail: function () {
                    setTimeout(function () { // 做了个延时重试一次，作为保底。
                        wx.showTabBar()
                    }, 500)
                }
            });
            this.setData({
                pickerActive: 0,
                maskActive: 0,
            })
        },

        //关闭卡片详细查看
        CloseCardItemTap() {
            this.setData({
                cardShowActive: 0,
            })
        },

        //改变时间
        ChangeDateItemTap(e) {
            this.setData({
                showDate: this.data.pickerDate,
            })
            this.getDateScroll();
            this.ClosePickerItemTap();
        },

        //计算滚动日期
        getDateScroll() {
            console.log(this.data.groupDataArr);
            let i;
            for (i = 0; i < this.data.groupDataArr.length; i++) {
                var year = parseInt(this.data.groupDataArr[i][0].substring(0, 4));
                var month = parseInt(this.data.groupDataArr[i][0].substring(5, 7));
                if (this.data.showDate[1] + 2015 < year || (this.data.showDate[1] + 2015 == year && this.data.showDate[0] + 1 < month)) {
                    continue;
                } else {
                    break;
                }
            }
            if (i >= this.data.groupDataArr.length) {
                i--;
            }
            this.setData({
                posScroll: "item" + i,
            })
            console.log(this.data.posScroll);
            this.scrollToPos();
        },

        //滚动到指定位置
        scrollToPos() {
            var query = this.createSelectorQuery();
            query.select('.btn_line').boundingClientRect()
            setTimeout(() => {
                    query.exec((res) => {
                        var distance_tmp = res[0].bottom;
                        var query2 = this.createSelectorQuery();
                        //选择id
                        query2.select('#' + this.data.posScroll).boundingClientRect()
                        setTimeout(() => {
                            query2.exec((resc) => {
                                //res就是 所有标签为mjltest的元素的信息 的数组
                                var top = resc[0].top;
                                var distance = parseFloat(distance_tmp) - 32 - parseFloat(top);
                                setTimeout(() => {
                                    wx.pageScrollTo({
                                        scrollTop: -distance,
                                        duration: 1000,
                                    })
                                }, 100);

                            })
                        }, 100)

                    })
                }, 100
            )
        },

        //定位点击的卡片
        cardItemTap(e) {
            console.log(e);
            if(this.data.collectFlag==0){
                const index = e.currentTarget.dataset.index.id;
                for (let i = 0; i < this.data.proData.length; i++) {
                    if (this.data.proData[i].id == index) {
                        this.setData({
                            cardShowActive: 1,
                            cardShowId: i,
                            cardFront:i,
                            cardBack:i,
                        })
                        break;
                    }
                }
            }
            else{
                const index = e.currentTarget.dataset.index.id;
                for (let i = 0; i < this.data.message_data_collect.length; i++) {
                    if (this.data.message_data_collect[i].id == index) {
                        this.setData({
                            cardShowActive: 1,
                            cardShowId: i,
                            cardFront:i,
                            cardBack:i,
                        })
                        break;
                    }
                }
            }
        },

        //收藏
        cardItemLongTap(e) {
            app.globalData.userCardChangeFlag=1;
            const id=parseInt(e.currentTarget.dataset.index.id);
            var isCollect = e.currentTarget.dataset.index.collect;
            let params={
                url:'/userCardCollect',
                method: 'PUT',
                data: {
                    id:id
                },
            }
            console.log(id);
            if (isCollect == 0) {
                var that=this;
                request(params).then(()=>{
                   var index=that.data.proData.findIndex(
                       (obj,index)=>{
                           return obj.id==id;
                       }
                   );
                    let l="proData["+index+"].collect"
                    that.setData({
                        [l]:1
                    })
                    console.log(that.data.proData[index])
                    that.splitDataArray()
                });
                wx.showToast({
                    title: '收藏成功',
                    icon: 'none',
                    duration: 1500,
                })
            } else {
                var that=this;
                request(params).then(()=>{
                    var index=that.data.proData.findIndex(
                        (obj,index)=>{
                            return obj.id==id;
                        }
                    );
                    let l="proData["+index+"].collect"
                    that.setData({
                        [l]:0
                    })
                    console.log(that.data.proData[index])
                    that.splitDataArray()
                });
                wx.showToast({
                    title: '取消收藏',
                    icon: 'none',
                    duration: 1500,

                })
            }
        },
        //阻止滑动
        preventTouchMove() {
        },
        //分享
        shareItemTap(e) {
            wx.showToast({  // 显示加载中loading效果2秒
                title: '正在下载',
                icon: 'loading',
                duration: 1000    //提示的延迟时间
            });
            console.log(e)
            wx.downloadFile({
                url: e.currentTarget.dataset.index.imageSrc,
                success: (res) => {
                    wx.showShareImageMenu({
                        path: res.tempFilePath,
                        success: () => {
                        },
                        fail: (res) => {
                            console.log(res)
                            if (res.errMsg.indexOf('deny') != -1 || res.errMsg.indexOf('denied') != -1) {
                                wx.showToast({
                                    title: '分享失败！',
                                    icon: 'none',
                                    duration: 2000,
                                })
                            } else {
                                wx.showToast({
                                    title: '分享失败！',
                                    icon: 'none',
                                    duration: 2000,
                                });
                            }
                        },
                    })
                }
            })
        },

        //是否查看收藏
        DataCollectPickerItemTap(){
            if(this.data.collectFlag==0){
                this.setData({
                    collectFlag:1,
                })
            }else{
                this.setData({
                    collectFlag:0,
                })
            }
        },

        //旋转
        rotateItemTap(e){
            console.log(this.data.WindowWidth);
            const x = e.detail.x;
            if(x<this.data.WindowWidth/2){
                this.rotateTurnLeft();
            }else{
                this.rotateTurnRight();
            }
        },
        //左旋转
        rotateTurnLeft(){
            let pos=this.data.cardShowId-1;
            if(pos<0){
                wx.showToast({
                    title: "第一张",
                    icon:"none",
                    duration:1000
                })
                return;
            }
            if(this.data.CardFrontFlag===1){
                this.setData({
                    cardFront:this.data.cardShowId,
                    cardBack:pos,
                    cardShowId:pos,
                    CardFrontFlag:0,
                })
            } else{
                this.setData({
                    cardBack:this.data.cardShowId,
                    cardFront:pos,
                    cardShowId:pos,
                    CardFrontFlag:1,
                })
            }
            var angleA=this.data.RotateCardFront-180
            var angleB=this.data.RotateCardBack-180
            this.setData({
                styleCardFront:'transform:rotateY('+angleA+'deg)',
                styleCardBack:'transform:rotateY('+angleB+'deg)',
                RotateCardFront:angleA,
                RotateCardBack:angleB,
            })
        },

        //右旋转
        rotateTurnRight(){
            let pos=this.data.cardShowId+1;
            if(this.data.collectFlag==0){
                if(pos>=this.data.proData.length){
                    wx.showToast({
                        icon:"none",
                        title: "最后一张了",
                        duration:1000
                    })
                    return;
                }
            }else {
                if(pos>=this.data.message_data_collect.length){
                    wx.showToast({
                        icon:"none",
                        title: "最后一张了",
                        duration:1000
                    })
                    return;
                }
            }
            if(this.data.CardFrontFlag===1){
                this.setData({
                    cardFront:this.data.cardShowId,
                    cardBack:pos,
                    cardShowId:pos,
                    CardFrontFlag:0,
                })
            }
            else{
                this.setData({
                    cardBack:this.data.cardShowId,
                    cardFront:pos,
                    cardShowId:pos,
                    CardFrontFlag:1,
                })
            }
            var angleA=this.data.RotateCardFront+180
            var angleB=this.data.RotateCardBack+180
            this.setData({
                styleCardFront:'transform:rotateY('+angleA+'deg)',
                styleCardBack:'transform:rotateY('+angleB+'deg)',
                RotateCardFront:angleA,
                RotateCardBack:angleB,
            })
        },

        returnData(){
            console.log("点击了组件")
            if(this.data.proData!=null)
                return this.data.proData
        },

    }
})
